import os
import json
from datetime import datetime, timedelta
from urllib.parse import urljoin
import requests

from utils.password_ascii import convert_to_custom_format


class JapdApi:
    BASE_URL = "http://10.6.10.110/api/jadp/"

    def __init__(self):
        self.session = requests.Session()
        self.headers = {
            'Host': '10.6.10.110',
            'Origin': 'http://10.6.10.110',
            'Ratio': '960*1707',
            'Referer': 'http://10.6.10.110/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81'
        }
        self.token = self.session_login()

        self.system_management_params = self.extract_system_management_params()
        self.user_data = self.user_info_name()
        self.update_user_info_cache()

    def session_login(self):
        url = urljoin(self.BASE_URL, "auth/session")
        data = {"account": "SuperAdmin", "password": convert_to_custom_format("hello")}
        res = self.session.post(url=url, json=data, headers=self.headers).text
        return res

    def get_company_per(self):
        url = urljoin(self.BASE_URL, "personnel/users/search")
        params = {
            'pageNo': 1,
            'pageSize': 200000,
            'orgId': 20000001,
            'state': 1,
            'userState': 1,
            'fastQueryValue': '',
            'associateType': 1,
            '_': 1702261242508
        }
        res = json.loads(self.session.get(url=url, params=params, headers=self.headers).text)
        return res

    def update_user_info_cache(self):
        # 检查是否需要更新数据
        if not self.is_cache_valid("user_info_cache.txt", 1):
            user_info = self.get_company_per()
            with open("user_info_cache.txt", "w") as cache_file:
                json.dump(user_info, cache_file)

    def is_cache_valid(self, cache_path, days):
        # 检查缓存是否存在且未过期
        if os.path.exists(cache_path):
            last_modified_time = os.path.getmtime(cache_path)
            last_modified_date = datetime.fromtimestamp(last_modified_time)
            expiration_date = last_modified_date + timedelta(days=days)
            current_date = datetime.now()
            return current_date <= expiration_date
        return False

    def get_user_info(self):
        # 如果缓存有效，直接从缓存中加载数据
        if self.is_cache_valid("user_info_cache.txt", 5):
            with open("user_info_cache.txt", "r") as cache_file:
                return json.load(cache_file)

        # 缓存无效，从接口获取新数据并更新缓存
        user_info = self.get_company_per()
        with open("user_info_cache.txt", "w") as cache_file:
            json.dump(user_info, cache_file)

        return user_info

    def user_info_name(self):
        user_info = self.get_user_info()
        return [
            {
                "id": user_name["userId"],
                'name': user_name["employeeName"],
                'account': user_name["account"],
                'name_full_path': user_name["nameFullPath"]
            }
            for user_name in user_info["list"]
        ]

    # 根据组织名称获取id
    def get_name_by_path(self, search_value):
        matching_names = [
            item.get('id') for item in self.user_data
            if item.get('name_full_path') and search_value in item['name_full_path']
        ]
        return matching_names

    def get_id_by_account(self, search_value):
        matching_names = []

        # Ensure search_value is a non-empty string
        if not search_value or not isinstance(search_value, str):
            return matching_names

        # Use case-insensitive matching for account names
        search_value_lower = search_value.lower()

        for item in self.user_data:
            if 'account' in item and isinstance(item['account'], str):
                if search_value_lower == item['account'].lower():
                    matching_names.append(item.get('id'))

        return matching_names

    def get_name_by_account(self, search_value):
        matching_names = []

        # Ensure search_value is a non-empty string
        if not search_value or not isinstance(search_value, str):
            return matching_names

        # Use case-insensitive matching for account names
        search_value_lower = search_value.lower()

        for item in self.user_data:
            if 'account' in item and isinstance(item['account'], str):
                if search_value_lower == item['account'].lower():
                    matching_names.append(item.get('name'))

        return matching_names

    def get_name(self, search_value):
        matching_names = [
            item.get('name') for item in self.user_data
            if item.get('name_full_path') and item['name_full_path'].endswith(search_value)
        ]
        return matching_names

    def get_name_(self, search_value):
        matching_names = [
            item.get('name') for item in self.user_data
            if item.get('name') and item['name'].endswith(search_value)
        ]
        return matching_names

    def get_id_by_path(self, search_value):
        for role_info in self.system_management_params["role_info_list"]:
            if role_info['roleName'] == search_value:
                return role_info['roleId']
        return None

    # noinspection PyShadowingNames,DuplicatedCode
    def extract_system_management_params(self):
        url = urljoin(self.BASE_URL, "permission/roles/search")
        data = {
            'pageNo': 1,
            'pageSize': 2000,
            'roleClassifyId': 'AF7F3C52C77B409AABBFF2EB38D3DEA5',
            'fastQueryValue': '',
            'cascadeQuery': 0,
            '_': 1702278165589
        }
        res = json.loads(self.session.get(url=url, params=data, headers=self.headers).text)
        if res:
            role_info_list = [
                {
                    "roleId": info_list.get("roleId"),
                    "roleName": info_list.get("roleName"),
                }
                for info_list in res.get("list")
            ]
            role_name_list = [info_list["roleName"] for info_list in res.get("list")]
            return {"role_info_list": role_info_list, "role_name_list": role_name_list}
        else:
            return {"role_info_list": [], "role_name_list": []}

    def extract_system_management_params_name(self):
        return self.system_management_params["role_name_list"]

    # noinspection PyShadowingNames,PyTypeChecker
    def per_import(self, role_name, depa_name):
        """
        :type depa_name: object
        :type role_name: 制度权限列表数据
        """
        department_id = self.get_id_by_path(role_name)
        name = ','.join(map(str, self.get_name_by_account(depa_name)))
        user_id = self.get_id_by_account(depa_name)
        url = urljoin(self.BASE_URL, f"permission/subjectRole?roleId={department_id}")
        res = self.session.post(url=url, json=user_id, headers=self.headers).status_code
        if res == 200:
            return f"名字：【{name}】，添加到【{role_name}】权限成功!"

    # noinspection PyShadowingNames
    def dept_per_import(self, role_name, depa_name):
        """
        :type depa_name: object
        :type role_name: 制度权限列表数据
        """
        department_id = self.get_id_by_path(role_name)
        name = ', '.join(map(str, self.get_name(depa_name)))
        user_id = self.get_name_by_path(depa_name)
        url = urljoin(self.BASE_URL, f"permission/subjectRole?roleId={department_id}")
        res = self.session.post(url=url, json=user_id, headers=self.headers).status_code
        if res == 200:
            return f"【{depa_name}】的人员：【{name}】添加到【{role_name}】权限成功!"


if __name__ == "__main__":
    japd_instance = JapdApi()
    role_name_list = japd_instance.extract_system_management_params_name()
    for role_name in role_name_list:
        # 账号
        print(japd_instance.per_import(role_name, "cuijin"))
        # 部门路径
        # print(japd_instance.dept_per_import(role_name, "哈尔滨电气集团有限公司/哈电集团（本部）/法律合规部"))
